package com.cos.emp.services.impl;

import com.cos.emp.dao.EmpDao;
import com.cos.emp.entity.Emp;
import com.cos.emp.services.EmpServices;
import com.cos.emp.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * @author: COS
 * @time: 2022/6/1 14:27
 * @description:
 */
public class EmpServicesImpl implements EmpServices {
    @Override
    public boolean addEmp(Emp e) {
        boolean flag = false;
        try {
            if (e != null) {
                EmpDao mapper = MyBatisUtil.getMapper(EmpDao.class);
                int i = mapper.addEmp(e);
                MyBatisUtil.commit();
                if (i>0) {
                    return true;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            MyBatisUtil.rollback();
        }
        return flag;
    }

    @Override
    public boolean delEmp(Integer eno) {
        boolean flag = false;
        try {
            flag = false;
            if (eno > 0) {
                EmpDao mapper = MyBatisUtil.getMapper(EmpDao.class);
                int i = mapper.delEmp(eno);
                MyBatisUtil.commit();
                if (i > 0) {
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            MyBatisUtil.rollback();
        }
        return flag;
    }

    @Override
    public PageInfo<Emp> getEmpByPages(Integer pageNum, int pages) {
        try {
            EmpDao mapper = MyBatisUtil.getMapper(EmpDao.class);
            PageHelper.startPage(pageNum, pages);
            List<Emp> all = mapper.getAll();
            PageInfo<Emp> info = new PageInfo<>(all);
            return info;
        } finally {
            MyBatisUtil.close();
        }
    }

    @Override
    public Emp doLogin(String ename, String pwd) {
        try {
            EmpDao mapper = MyBatisUtil.getMapper(EmpDao.class);
            Emp e = mapper.getEmpByEname(ename);
            if (e != null && e.getPwd().equals(pwd)) {
                //用户名记密码都是正确
                return e;
            }
            return null;
        } finally {
            MyBatisUtil.close();
        }
    }
}
